import Sequelize = require('sequelize')
const feathers_sequelize_service = require('feathers-sequelize')
const fs = require('fs')
const path = require('path')
const defineDir = path.resolve(__dirname, "./define")
const { remove, discard } = require('feathers-hooks-common')
import record_time = require('../hooks/record_time')

function connectMySQL(app: any) {
    const connectionString = app.get('mysql');
    const sequelize = new Sequelize(connectionString, {
        dialect: 'mysql',
        pool: {
            max: 5,
            min: 0,
            idle: 10000
        },
        logging: console.log,
        define: {
            freezeTableName: false,
            timestamps: false,
        }
    });
    const oldSetup = app.setup;

    app.set('sequelizeClient', sequelize);

    app.setup = function (...args: any[]) {
        const result = oldSetup.apply(this, args);

        // Set up data relationships
        const models = sequelize.models;
        Object.keys(models).forEach(name => {
            if ('associate' in models[name]) {
                let tmp: any = models[name]
                tmp.associate(models);
            }
        });

        return result;
    };
};

const openService: string[] = [
    'buyer',
    'push',
    'menu'
]

export = function () {
    const app = this

    connectMySQL(app)

    let sequelize = app.get('sequelizeClient')
    let files = fs.readdirSync(defineDir)
    files.forEach((item: string) => {
        if (item.endsWith('.js')) {
            let lastDotIndex = item.lastIndexOf('.')
            if (lastDotIndex > 0) {
                let moduleName = item.substring(0, lastDotIndex)
                let Model = require(`./define/${moduleName}`)(sequelize)
                if (openService.some(item => item == moduleName)) {
                    let serviceName = `/database/${moduleName}`
                    app.use(serviceName, feathers_sequelize_service({
                        Model,
                        paginate: {
                            default: 15,
                            max: 15
                        }
                    }))
                }
            }
        }
    })
    sequelize.sync({ force: false }).then((model: any) => {
        console.log('db sync success!')
    })
}